package org.hank.wanandroid.ui

import android.os.Bundle
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.activity_my_collect.*
import org.hank.commom.base.BaseActivity
import org.hank.commom.listener.ReloadListener
import org.hank.wanandroid.R
import org.hank.wanandroid.listener.OnArticleRecyclerListener
import org.hank.wanandroid.ui.widget.ArticleRecycleWidget
import org.hank.wanandroid.viewmodel.CollectViewModel

class MyCollectActivity : BaseActivity(), OnArticleRecyclerListener, ReloadListener {
    override val layoutResId: Int
        get() = R.layout.activity_my_collect
    var pageNum = 0
    var totalPage = -1
    var articelRecycleWidget = ArticleRecycleWidget(this)
    lateinit var refresh: SmartRefreshLayout

    private val collectViewModel by getViewModel(CollectViewModel::class.java) {
        liveDataCollect.observe(it) {
            totalPage = it.total
            if (!it.datas.isNullOrEmpty() && it.datas!!.size > 0)
                loadingTip.dismiss()
            else
                loadingTip.showEmpty()

            articelRecycleWidget.validateData(it.datas, true)
            if (pageNum < totalPage - 1)
                pageNum += 1
            dismissLoadRefresh()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ivBack.setOnClickListener { finish() }
        reload()
        refresh = smartrefresh_mycollect
        refresh.setOnRefreshListener {
            reload()
            articelRecycleWidget.notifyReload()
        }
        loadingTip.setReloadListener(this)
        refresh.setOnLoadMoreListener {
            if (pageNum != totalPage - 1) {
                collectViewModel.getMyCollect(pageNum)
            } else {
                articelRecycleWidget.validateData(null)
                refresh.finishLoadMore()
            }
        }
        var ft = supportFragmentManager.beginTransaction()
        ft.add(R.id.frame_my_collect, articelRecycleWidget)
        ft.commit()
    }

    override fun onReload() {
        reload()
    }

    override fun reload() {
        pageNum = 0
        loadingTip.loading()
        collectViewModel.getMyCollect(pageNum)
    }

    fun dismissLoadRefresh() {
        refresh.finishLoadMore()
        refresh.finishRefresh()
    }

    override fun showToast(msg: String) {
        super.showToast(msg)
        dismissLoadRefresh()
        articelRecycleWidget.validateData(null)
        loadingTip.showInternetError()
    }
}